package sj;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class demo2 {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        //得到一个DOM工厂
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newDefaultInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db=dbf.newDocumentBuilder();
        //
        Document doc=  db.parse("src/sj/demo1.xml");
        Element brandElement=doc.createElement("Brand");
        brandElement.setAttribute("name","三星");
        Element typeElement=doc.createElement("Type");
        typeElement.setAttribute("name","NoteX");
        brandElement.appendChild(typeElement);

        Element phoneInfoElement= (Element) doc.getElementsByTagName("PhoneInfo").item(0);
        phoneInfoElement.appendChild(brandElement);




        NodeList list=doc.getElementsByTagName("Brand");
        for (int i = 0; i <list.getLength() ; i++) {
            Element brandName= (Element) list.item(i);
            String brandNames=brandName.getAttribute("name");
            if (brandNames.equals("三星")){
                brandElement.setAttribute("name","SAMSUNG");
            }
        }
//
        for (int i = 0; i < list.getLength(); i++) {
            Element brandName= (Element) list.item(i);
            String brandNames=brandName.getAttribute("name");
            if (brandNames.equals("SAMSUNG")){
                brandElement.getParentNode().removeChild(brandElement);
            }
        }
        //保存XML文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        DOMSource domSource=new DOMSource(doc);
        StreamResult result=new StreamResult(new FileOutputStream("src/sj/demo1.xml"));
        //吧DOM树转换为XML文件
        transformer.transform(domSource,result);
    }
}
